{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "z:\\python39\\lib\\site-packages\\huggingface_hub\\file_download.py:1142: FutureWarning: `resume_download` is deprecated and will be removed in version 1.0.0. Downloads always resume when possible. If you want to force a new download, use `force_download=True`.\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[101, 6848, 2885, 1920, 6825, 3862, 752, 1920, 2110, 4638, 1333, 1728, 2218, 3221, 3175, 912, 511, 102, 5011, 6381, 3315, 4638, 7241, 4669, 4802, 2141, 4272, 511, 102, 0]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'[CLS] 选 择 大 连 海 事 大 学 的 原 因 就 是 方 便 。 [SEP] 笔 记 本 的 键 盘 确 实 爽 。 [SEP] [PAD]'"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from transformers import BertTokenizer\n",
    "#加载与训练字典和分词方法\n",
    "tokenizer=BertTokenizer.from_pretrained(\n",
    "    pretrained_model_name_or_path='bert-base-chinese',\n",
    "    cache_dir=None,\n",
    "    force_download=False\n",
    ")\n",
    "sents=[\n",
    "    \"选择大连海事大学的原因就是方便。\",\n",
    "    \"笔记本的键盘确实爽。\",\n",
    "    \"房间太小，其他的确实一般。\",\n",
    "    \"今天才知道这书还有第6卷，有点郁闷\",\n",
    "    \"机器背面似乎还被撕了张什么标签，残胶还在。\"\n",
    "]\n",
    "#编码两个句子\n",
    "out=tokenizer.encode(\n",
    "    text=sents[0],\n",
    "    text_pair=sents[1],\n",
    "    # 当句子长度大于max_length时，截断\n",
    "    truncation=True,\n",
    "    # 一律补pad到max_length的长度\n",
    "    padding='max_length',\n",
    "    add_special_tokens=True,#少于max_length时，使用符号补全\n",
    "    max_length=30,\n",
    "    return_tensors=None\n",
    ")\n",
    "print(out)\n",
    "\"\"\"输入文本开头【cls】。不同句子或者文本片段的分割用[sep]\"\"\"\n",
    "tokenizer.decode(out)#解码\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "BertTokenizer(name_or_path='bert-base-chinese', vocab_size=21128, model_max_length=512, is_fast=False, padding_side='right', truncation_side='right', special_tokens={'unk_token': '[UNK]', 'sep_token': '[SEP]', 'pad_token': '[PAD]', 'cls_token': '[CLS]', 'mask_token': '[MASK]'}, clean_up_tokenization_spaces=True),  added_tokens_decoder={\n",
       "\t0: AddedToken(\"[PAD]\", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),\n",
       "\t100: AddedToken(\"[UNK]\", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),\n",
       "\t101: AddedToken(\"[CLS]\", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),\n",
       "\t102: AddedToken(\"[SEP]\", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),\n",
       "\t103: AddedToken(\"[MASK]\", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),\n",
       "}"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tokenizer"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "增强的编码函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "input_ids : [101, 6848, 2885, 1920, 6825, 3862, 752, 1920, 2110, 4638, 1333, 1728, 2218, 3221, 3175, 912, 511, 102, 5011, 6381, 3315, 4638, 7241, 4669, 4802, 2141, 4272, 511, 102, 0]\n",
      "token_type_ids : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]\n",
      "special_tokens_mask : [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1]\n",
      "attention_mask : [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]\n",
      "[CLS] 选 择 大 连 海 事 大 学 的 原 因 就 是 方 便 。 [SEP] 笔 记 本 的 键 盘 确 实 爽 。 [SEP] [PAD]\n"
     ]
    }
   ],
   "source": [
    "out=tokenizer.encode_plus(\n",
    "    text=sents[0],\n",
    "    text_pair=sents[1],\n",
    "    # 大于max_length时候，截断\n",
    "    truncation=True,\n",
    "    # 补齐到max_length长度\n",
    "    padding=\"max_length\",\n",
    "    max_length=30,\n",
    "    add_special_tokens=True,\n",
    "    # 可取值为tf,pt,np,jax。默认是List\n",
    "    return_tensors=None,\n",
    "    # 返回token_type_ids，区分不同句子\n",
    "    return_token_type_ids=True,\n",
    "    # 返回attention_mask，注意力掩码,padding（补全的位置）是0，非padding（句子）是1\n",
    "    return_attention_mask=True,\n",
    "    # 返回special_tokens_mask，特殊标记掩码，标记cls,sep(1)\n",
    "    return_special_tokens_mask=True,\n",
    ")\n",
    "for k,v in out.items():\n",
    "    print(k,\":\",v)\n",
    "print(tokenizer.decode(out[\"input_ids\"]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "批量编码句子"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "out=tokenizer.batch_encode_plus(\n",
    "    batch_text_or_text_pairs=[sents[0],sents[1]],\n",
    "    add_special_tokens=True,\n",
    "    # 当句子长度大于max_length时候,截断\n",
    "    truncation=True,\n",
    "    # 一律补零到max_length长度\n",
    "    padding='max_length',\n",
    "    max_length=15,\n",
    "    # 可以取值tf,pt,np,jax。默认list\n",
    "    return_tensors=None,\n",
    "    # 返回token_type_ids\n",
    "    return_token_type_ids=True,\n",
    "    # 返回attention_mask\n",
    "    return_attention_mask=True,\n",
    "    # 返回special_tokens_mask,特殊符号标识\n",
    "    return_special_tokens_mask=True\n",
    "\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "input_ids ： [[101, 6848, 2885, 1920, 6825, 3862, 752, 1920, 2110, 4638, 1333, 1728, 2218, 3221, 102], [101, 5011, 6381, 3315, 4638, 7241, 4669, 4802, 2141, 4272, 511, 102, 0, 0, 0]]\n",
      "token_type_ids ： [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]\n",
      "special_tokens_mask ： [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]]\n",
      "attention_mask ： [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0]]\n",
      "[CLS] 选 择 大 连 海 事 大 学 的 原 因 就 是 [SEP]\n",
      "[CLS] 笔 记 本 的 键 盘 确 实 爽 。 [SEP] [PAD] [PAD] [PAD]\n"
     ]
    }
   ],
   "source": [
    "for k,v in out.items():\n",
    "    print(k,\"：\",v)\n",
    "print(tokenizer.decode(out['input_ids'][0]))\n",
    "print(tokenizer.decode(out['input_ids'][1]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "批量成对儿编码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "out=tokenizer.batch_encode_plus(\n",
    "    batch_text_or_text_pairs=[(sents[0],sents[1]),(sents[2],sents[3])],\n",
    "    add_special_tokens=True,\n",
    "    # 当句子长度大于max_length时候,截断\n",
    "    truncation=True,\n",
    "    # 一律补零到max_length长度\n",
    "    padding='max_length',\n",
    "    max_length=40,\n",
    "    # 可以取值tf,pt,np,jax。默认list\n",
    "    return_tensors=None,\n",
    "    # 返回token_type_ids\n",
    "    return_token_type_ids=True,\n",
    "    # 返回attention_mask\n",
    "    return_attention_mask=True,\n",
    "    # 返回special_tokens_mask,特殊符号标识\n",
    "    return_special_tokens_mask=True\n",
    "\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "input_ids : [[101, 6848, 2885, 1920, 6825, 3862, 752, 1920, 2110, 4638, 1333, 1728, 2218, 3221, 3175, 912, 511, 102, 5011, 6381, 3315, 4638, 7241, 4669, 4802, 2141, 4272, 511, 102, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [101, 2791, 7313, 1922, 2207, 8024, 1071, 800, 4638, 4802, 2141, 671, 5663, 511, 102, 791, 1921, 2798, 4761, 6887, 6821, 741, 6820, 3300, 5018, 127, 1318, 8024, 3300, 4157, 6944, 7315, 102, 0, 0, 0, 0, 0, 0, 0]]\n",
      "token_type_ids : [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]]\n",
      "special_tokens_mask : [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1]]\n",
      "attention_mask : [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]]\n"
     ]
    }
   ],
   "source": [
    "for k,v in out.items():\n",
    "    print(k,\":\",v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[CLS] 选 择 大 连 海 事 大 学 的 原 因 就 是 方 便 。 [SEP] 笔 记 本 的 键 盘 确 实 爽 。 [SEP] [PAD] [PAD] [PAD] [PAD] [PAD] [PAD] [PAD] [PAD] [PAD] [PAD] [PAD]\n"
     ]
    }
   ],
   "source": [
    "print(tokenizer.decode(out[\"input_ids\"][0]))#打印第一个句子对儿"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "字典操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(dict, 21128, False)"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "zidian=tokenizer.get_vocab()#字典中都是一个个的字，并非词\n",
    "type(zidian),len(zidian),\"月光\"in zidian"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(dict, 21132, 21129, 21128)"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"\"\"添加新词\"\"\"\n",
    "tokenizer.add_tokens(new_tokens=[\"阿里巴巴\",\"范小勤\",\"马老板\"])\n",
    "\n",
    "\"\"\"添加新符号\"\"\"\n",
    "tokenizer.add_special_tokens({\"eos_token\":\"[EOS]\"})\n",
    "\n",
    "zidian=tokenizer.get_vocab()\n",
    "\"\"\"添加后添加的词的位置就可以看见了\"\"\"\n",
    "type(zidian),len(zidian),zidian[\"范小勤\"],zidian[\"阿里巴巴\"]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[101, 21128, 3221, 702, 2571, 727, 4638, 7471, 2399, 8024, 21130, 2218, 3221, 21129, 1506, 1506, 1506, 21131, 102, 0, 0, 0, 0, 0, 0]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'[CLS] 阿里巴巴 是 个 快 乐 的 青 年 ， 马老板 就 是 范小勤 哈 哈 哈 [EOS] [SEP] [PAD] [PAD] [PAD] [PAD] [PAD] [PAD]'"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#编码后新添加的词\n",
    "out=tokenizer.encode(\n",
    "    text='阿里巴巴是个快乐的青年，马老板就是范小勤哈哈哈[EOS]',\n",
    "    text_pair=None,\n",
    "\n",
    "    #当句子长度大于max_length时候截断\n",
    "    truncation=True,\n",
    "\n",
    "    # 一律补齐pad到max_length最大长度\n",
    "    padding=\"max_length\",\n",
    "    add_special_tokens=True,\n",
    "    max_length=25,\n",
    "    return_tensors=None\n",
    "\n",
    ")\n",
    "print(out)\n",
    "tokenizer.decode(out)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
